import threading
import time

sendSerialFunc = None

touchDown = ''

toucchUp = ''

isInit = False

dtime = 30
utime = 30
with open('time.txt') as f:
    lines = f.readlines()
    line1 = lines[0].strip()
    tmps = line1.split(',')
    dtime = int(tmps[0])/1000.0
    utime = int(tmps[1])/1000.0

class StoppableThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        """请求线程停止"""
        self._stop_event.set()

    def stopped(self):
        """检查线程是否被要求停止"""
        return self._stop_event.is_set()


# 全局变量保存线程实例
thread_instance = None



def start_thread():
    """启动线程的函数"""
    global thread_instance
    
    def worker():
        """线程的工作函数"""
        while not threading.current_thread().stopped():
            # print("线程正在运行...")
            sendSerialFunc(touchDown)
            time.sleep(dtime)
            sendSerialFunc(toucchUp)
            time.sleep(utime)
        print("线程已停止")
    
    if thread_instance is None or not thread_instance.is_alive():
        thread_instance = StoppableThread(target=worker)
        thread_instance.start()
        print("线程已启动")
    else:
        print("线程已经在运行中")


def stop_thread():
    """停止线程的函数"""
    global thread_instance
    if thread_instance is not None and thread_instance.is_alive():
        thread_instance.stop()
        thread_instance.join()  # 等待线程结束
        print("已发送停止信号")
    else:
        print("没有活动的线程可以停止")


# 使用示例
if __name__ == "__main__":
    start_thread()  # 启动线程
    time.sleep(5)   # 让线程运行5秒
    stop_thread()   # 停止线程